package io.lvdaxian.mybatis07.executor.statement;

import io.lvdaxian.mybatis07.executor.Executor;
import io.lvdaxian.mybatis07.mapping.BoundSql;
import io.lvdaxian.mybatis07.mapping.MappedStatement;
import io.lvdaxian.mybatis07.session.ResultHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class PreparedStatementHandler extends BaseStatementHandler {
  
  public PreparedStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, ResultHandler resultHandler, BoundSql boundSql) {
    super(executor, mappedStatement, parameterObject, resultHandler, boundSql);
  }
  
  /**
   * 这个方法是 prepareStatement 的实现(可以放置 sql注入)
   *
   * @param connection 连接
   * @return 返回 statement
   * @throws SQLException 异常
   * @author lihh
   */
  @Override
  protected Statement instantiateStatement(Connection connection) throws SQLException {
    return connection.prepareStatement(boundSql.getSql());
  }
  
  /**
   * 目前 这个方法中 不做任何处理
   *
   * @param statement statement 语句
   * @throws SQLException 异常
   * @author lihh
   */
  @Override
  public void parameterize(Statement statement) throws SQLException {
    PreparedStatement ps = (PreparedStatement) statement;
    ps.setLong(1, Long.parseLong(((Object[]) parameterObject)[0].toString()));
  }
  
  /**
   * 这里进行数据查询
   *
   * @param statement     statement 语句
   * @param resultHandler 处理结果事件
   * @param <E>           动态泛型
   * @return 结果集
   * @throws SQLException 异常
   * @author lihh
   */
  @Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    PreparedStatement ps = (PreparedStatement) statement;
    ps.execute();
    return resultSetHandler.handleResultSets(ps);
  }
}
